<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户游戏数据列表</span>
          <div class="right">
            <el-button type="primary" @click="handleExport">导出数据</el-button>
            <el-button type="success" @click="handleDataAnalysis">数据分析</el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="userList"
        stripe
        style="width: 100%"
        highlight-current-row
        :row-class-name="tableRowClassName"
        border
        @row-click="handleRowClick"
      >
        <el-table-column type="index" width="50" align="center" />
        <el-table-column prop="username" label="用户名称" min-width="120" show-overflow-tooltip />
        <el-table-column label="用户头像" width="80" align="center">
          <template #default="scope">
            <el-avatar :size="40" :src="scope.row.avatar">
              {{ scope.row.username && scope.row.username.charAt(0).toUpperCase() }}
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="用户等级" width="80" align="center">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.level }}级</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalGames" label="游戏数量" min-width="90" align="center" />
        <el-table-column prop="totalPlayTime" label="总游戏时长" min-width="120" align="center">
          <template #default="scope">
            {{ formatTotalTime(scope.row.totalPlayTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="lastActive" label="最近活跃" min-width="120" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.lastActive) }}
          </template>
        </el-table-column>
        <el-table-column label="活跃度" min-width="100" align="center">
          <template #default="scope">
            <el-tag :type="getActivityTagType(scope.row.activityLevel)">
              {{ getActivityLevelText(scope.row.activityLevel) }}
            </el-tag>
            <div v-if="scope.row.activityLevel === 'high'" class="active-indicator">
              <i class="el-icon-refresh" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="achievementCount" label="成就数量" min-width="90" align="center" />
        <el-table-column label="游戏偏好" min-width="120" align="center">
          <template #default="scope">
            <el-tooltip
              v-for="(preference, index) in (scope.row.gamePreferences || []).slice(0, 2)"
              :key="index"
              :content="preference"
              placement="top"
            >
              <el-tag class="ml-5" size="small" :type="getGamePreferenceType(index)">
                {{ preference }}
              </el-tag>
            </el-tooltip>
            <el-tooltip
              v-if="scope.row.gamePreferences && scope.row.gamePreferences.length > 2"
              :content="scope.row.gamePreferences.slice(2).join('、')"
              placement="top"
            >
              <el-tag class="ml-5" size="small" type="info">
                +{{ scope.row.gamePreferences.length - 2 }}
              </el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180" align="center">
          <template #default="scope">
            <el-button type="primary" link @click.stop="handleRowClick(scope.row)">详情</el-button>
            <el-button type="success" link @click.stop="handleStats(scope.row)">统计</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          background
          :layout="'total, sizes, prev, pager, next, jumper'"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 数据分析弹窗 -->
    <el-dialog v-model="dataAnalysisVisible" title="用户游戏数据分析" width="800px">
      <div v-loading="analysisLoading" class="analysis-container">
        <div class="analysis-item">
          <h3>用户游戏类型偏好分布</h3>
          <div
            v-if="typeDistributionData.length > 0"
            ref="typeChartRef"
            class="chart-container"
          ></div>
          <div v-else class="chart-placeholder">暂无数据</div>
        </div>
        <div class="analysis-item">
          <h3>用户活跃度分布</h3>
          <div
            v-if="activityDistributionData.length > 0"
            ref="activityChartRef"
            class="chart-container"
          ></div>
          <div v-else class="chart-placeholder">暂无数据</div>
        </div>
        <div class="analysis-item">
          <h3>每月新增用户趋势</h3>
          <div v-if="monthlyTrendData.length > 0" ref="trendChartRef" class="chart-container"></div>
          <div v-else class="chart-placeholder">暂无数据</div>
        </div>
        <div class="analysis-item">
          <h3>用户游戏时长分布</h3>
          <div
            v-if="playTimeDistributionData.length > 0"
            ref="timeChartRef"
            class="chart-container"
          ></div>
          <div v-else class="chart-placeholder">暂无数据</div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dataAnalysisVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleExportAnalysis">导出分析报告</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import UserGameAPI, { type GameUserInfo, type GameUserInfoQuery } from "@/api/game/userinfo";

const router = useRouter();
const loading = ref(false);
const total = ref(0);
const dateRange = ref<any[]>([]);
const userList = ref<GameUserInfo[]>([]);
const dataAnalysisVisible = ref(false);

// 数据分析相关
const typeDistributionData = ref<any[]>([]);
const activityDistributionData = ref<any[]>([]);
const monthlyTrendData = ref<any[]>([]);
const playTimeDistributionData = ref<any[]>([]);
const analysisLoading = ref(false);

// 查询参数
const queryParams = reactive<GameUserInfoQuery>({
  pageNum: 1,
  pageSize: 10,
  username: "",
  activityLevel: "",
  userLevel: undefined,
  startDate: "",
  endDate: "",
  sortField: "lastActive",
  sortOrder: "descending",
});

// 获取用户列表
const getUserList = async () => {
  loading.value = true;

  try {
    // 构建查询参数
    const params = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      username: queryParams.username,
      activityLevel: queryParams.activityLevel,
      userLevel: queryParams.userLevel,
      startDate: queryParams.startDate,
      endDate: queryParams.endDate,
      sortField: queryParams.sortField,
      sortOrder: queryParams.sortOrder,
    };

    console.log("请求用户列表参数:", params);
    console.log("API URL:", import.meta.env.VITE_APP_API_URL);

    // 使用API获取用户列表
    const response = await UserGameAPI.getUserList(params);
    console.log("用户列表接口返回数据:", response);

    // 处理返回数据
    if (response) {
      let records: any[] = [];
      let totalCount = 0;

      // 尝试所有可能的数据结构
      if (response.code === "00000" && response.data) {
        // 标准返回格式
        records = response.data.records || [];
        totalCount = response.data.total || 0;
      } else if (response.list && Array.isArray(response.list)) {
        // {list: [], total: number} 格式
        records = response.list;
        totalCount = response.total || records.length;
        console.log("从list属性获取数据:", records.length);
      } else if (response.records && Array.isArray(response.records)) {
        // {records: [], total: number} 格式
        records = response.records;
        totalCount = response.total || records.length;
      } else if (Array.isArray(response)) {
        // 直接返回数组的格式
        records = response;
        totalCount = response.length;
      } else if (typeof response === "object") {
        // 尝试遍历对象找到数组
        for (const key in response) {
          if (Array.isArray(response[key])) {
            records = response[key];
            totalCount = records.length;
            console.log(`从属性 ${key} 中提取数组数据`);
            break;
          }
        }
      }

      console.log("解析后的记录数量:", records.length);

      // 将后端数据结构映射到前端期望的结构
      userList.value = records.map((item: any) => {
        // 从日志中看到，后端返回的字段是: id, user_id, username, avatar, points, level, create_time, update_time
        return {
          id: item.id || item.user_id || 0,
          username: item.username || "",
          avatar: item.avatar || "",
          level: item.level || 0,
          points: item.points || 0,
          totalGames: item.totalGames || 0, // 这些字段可能不在原始数据中，使用默认值
          totalPlayTime: item.totalPlayTime || 0,
          lastActive: item.update_time || item.updateTime || "",
          activityLevel: item.activityLevel || "medium",
          achievementCount: item.achievementCount || 0,
          gamePreferences: item.gamePreferences || [],
          createTime: item.create_time || item.createTime || "",
          updateTime: item.update_time || item.updateTime || "",
        };
      });

      total.value = totalCount;
      console.log("处理后的用户列表数据:", userList.value);
    } else {
      userList.value = [];
      total.value = 0;
      console.warn("返回的数据为空");
    }

    loading.value = false;

    // 显示筛选结果提示
    if (queryParams.username || queryParams.activityLevel || queryParams.userLevel) {
      ElMessage({
        message: `筛选结果：找到 ${total.value} 条记录`,
        type: "info",
      });
    }
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败，请稍后重试");
    loading.value = false;
    userList.value = [];
    total.value = 0;
  }
};

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1;
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.startDate = dateRange.value[0];
    queryParams.endDate = dateRange.value[1];
  }
  getUserList();
};

// 重置查询
const resetQuery = () => {
  dateRange.value = [];
  queryParams.username = "";
  queryParams.activityLevel = "";
  queryParams.userLevel = undefined;
  queryParams.startDate = "";
  queryParams.endDate = "";
  handleQuery();
};

// 处理页码变化
const handleCurrentChange = (pageNum: number) => {
  queryParams.pageNum = pageNum;
  getUserList();
};

// 处理每页条数变化
const handleSizeChange = (pageSize: number) => {
  queryParams.pageSize = pageSize;
  getUserList();
};

// 查看用户详情
const handleDetail = (row: GameUserInfo) => {
  console.log("详情按钮点击，用户ID:", row.id);
  router.push({
    name: "UserDetail",
    params: { id: String(row.id) },
  });
};

// 查看用户统计
const handleStats = (row: GameUserInfo) => {
  console.log("统计按钮点击，用户ID:", row.id);
  // 检查ID是否有效
  if (!row.id) {
    ElMessage.warning("无效的用户ID");
    return;
  }
  router.push({
    name: "UserStatistics",
    params: { id: String(row.id) },
  });
};

// 加载分析数据
const loadAnalysisData = async () => {
  analysisLoading.value = true;

  try {
    // 获取游戏类型分布统计
    const typeResponse = await UserGameAPI.getGameTypeDistribution();
    if (typeResponse && typeResponse.data) {
      typeDistributionData.value = typeResponse.data;
    }

    // 获取用户活跃度分布
    const activityResponse = await UserGameAPI.getActivityDistribution();
    if (activityResponse && activityResponse.data) {
      activityDistributionData.value = activityResponse.data;
    }

    // 获取每月新增用户趋势
    const trendResponse = await UserGameAPI.getMonthlyTrend(12);
    if (trendResponse && trendResponse.data) {
      monthlyTrendData.value = trendResponse.data;
    }

    // 获取用户游戏时长分布
    const timeResponse = await UserGameAPI.getPlayTimeDistribution();
    if (timeResponse && timeResponse.data) {
      playTimeDistributionData.value = timeResponse.data;
    }

    analysisLoading.value = false;
  } catch (error) {
    console.error("获取统计数据失败:", error);
    ElMessage.error("获取统计数据失败，请稍后重试");
    analysisLoading.value = false;
  }
};

// 打开数据分析弹窗
const handleDataAnalysis = async () => {
  dataAnalysisVisible.value = true;
  loadAnalysisData();
};

// 导出分析报告
const handleExportAnalysis = async () => {
  try {
    const response = await UserGameAPI.exportAnalysisReport();
    if (response && response.data) {
      ElMessage.success("分析报告导出成功");
      // 这里可以处理下载链接
      window.open(response.data, "_blank");
    } else {
      ElMessage.error("导出失败，请稍后重试");
    }
  } catch (error) {
    console.error("导出分析报告失败:", error);
    ElMessage.error("导出失败，请稍后重试");
  }
  dataAnalysisVisible.value = false;
};

// 点击行
const handleRowClick = (row: GameUserInfo) => {
  handleDetail(row);
};

// 表格行的样式
const tableRowClassName = ({ row }: { row: GameUserInfo }) => {
  if (row.activityLevel === "high") {
    return "high-activity-row";
  }
  if (row.activityLevel === "low") {
    return "low-activity-row";
  }
  return "";
};

// 表格排序变化
const handleSortChange = ({ prop, order }: { prop: string; order: string }) => {
  queryParams.sortField = prop;
  queryParams.sortOrder = order;
  getUserList();
};

// 格式化总时间
const formatTotalTime = (seconds: number | undefined) => {
  if (seconds === undefined || seconds === null) return "-";
  const hours = Math.floor(seconds / 3600);
  return `${hours}小时`;
};

// 格式化日期
const formatDate = (date: string | undefined) => {
  if (!date) return "-";

  try {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");

    return `${year}-${month}-${day}`;
  } catch (e) {
    return "-";
  }
};

// 获取活跃度标签类型
const getActivityTagType = (level: string): string => {
  const types: Record<string, string> = {
    high: "success",
    medium: "warning",
    low: "info",
  };
  return types[level] || "info";
};

// 获取活跃度文本
const getActivityLevelText = (level: string): string => {
  const texts: Record<string, string> = {
    high: "高度活跃",
    medium: "中度活跃",
    low: "低度活跃",
  };
  return texts[level] || "未知";
};

// 获取游戏偏好标签类型
const getGamePreferenceType = (index: number): string => {
  const types = ["", "success", "warning", "danger", "info"];
  return types[index % types.length];
};

// 导出数据
const handleExport = async () => {
  try {
    const response = await UserGameAPI.exportUserData(queryParams);
    if (response && response.data) {
      ElMessage.success("数据导出成功");
      // 这里可以处理下载链接
      window.open(response.data, "_blank");
    } else {
      ElMessage.error("导出失败，请稍后重试");
    }
  } catch (error) {
    console.error("导出数据失败:", error);
    ElMessage.error("导出失败，请稍后重试");
  }
};

onMounted(() => {
  getUserList();
});
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.ml-5 {
  margin-left: 5px;
}

.analysis-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.analysis-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.analysis-item h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #303133;
}

.chart-container {
  height: 200px;
  width: 100%;
}

.chart-placeholder {
  height: 200px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  border-radius: 4px;
  position: relative;
  overflow: hidden;
}

.high-activity-row {
  background-color: rgba(103, 194, 58, 0.1);
}

.low-activity-row {
  background-color: rgba(144, 147, 153, 0.1);
}

.active-indicator {
  display: inline-block;
  margin-left: 5px;
  animation: spin 2s infinite linear;
  color: #67c23a;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
